const Base = require('../base.js');

module.exports = class extends Base {
  async indexAction() {
    // 判断类型 type 1为账号密码登录 2为手机号登录
    if (this.post('type') == 1) {
      // 用手机号去查询数据库验证账户是否存在
      var db = this.mongoose('mongo/sn_users');
      var findUser = await db.find({phone: this.post('phone')})
      console.log(this.post('phone'))
      console.log(findUser)
      if (findUser.length > 0) {
        var _user = findUser[0]
        if (think.sha256(this.post('pwd')) == _user.password) {
          var infoDb = this.mongoose('mongo/sn_users_info');
          var userInfo = await infoDb.find({uid: _user._id})
          var _info = {}
          if (userInfo.length > 0) {
            _info = userInfo[0]
          } else {
            var userInfo = new infoDb({
              uid: _user._id,
            })
            _info = await userInfo.save();
          }
          // 登录成功
          var token = await this.session('login', _user._id) // 把用户ID存进token
          return this.json({
            status: 1,
            msg: '登录成功',
            token,
            info: _info
          })
        } else {
          return this.json({
            status: -1,
            msg: '用户密码错误'
          })
        }
      } else {
        return this.json({
          status: -1,
          msg: '用户不存在，请用短信方式登录'
        })
      }
      // 验证密码是否正确
      // 登录账号写入token
    } else {
      // 验证验证码是否正确
      var codeObj = await this.session('code') // tokenj存储的Code对象
      codeObj = codeObj || {}
      if (Date.now() < codeObj.time) { // 判断验证码失效时间
        if (codeObj.code == this.post('code') && codeObj.phone == this.post('phone') ) { // 验证码正确
          var db = this.mongoose('mongo/sn_users');
          var findUser = await db.find({phone: this.post('phone')})
          var _user = {}
          if (findUser.length > 0) {
            _user = findUser[0]
          } else {
            // 用户还不存在，创建
            let dbuser = new db({
              phone: this.post('phone'),
              password: ""
            })
            _user = await dbuser.save()
          }
          var infoDb = this.mongoose('mongo/sn_users_info');
          var userInfo = await infoDb.find({uid: _user._id})
          var _info = {}
          if (userInfo.length > 0) {
            _info = userInfo[0]
          } else {
            var userInfo = new infoDb({
              uid: _user._id,
            })
            _info = await userInfo.save();
          }
          // 登录成功
          var token = await this.session('login', _user._id) // 把用户ID存进token
          return this.json({
            status: 1,
            msg: '登录成功',
            token,
            info: _info
          })

        } else {
          return this.json({
            status: -1,
            msg: '验证码错误'
          })
        }
      } else {
        return this.json({
          status: -1,
          msg: '验证码, 已失效!'
        })
      }
    }
  }
};
